class Offer < ActiveRecord::Base
  belongs_to :item
	belongs_to :region
	belongs_to :solarsystem


	def self.median(id)
			@total = 0
			@offers = find(:all, :conditions => "item_id = #{id}")
			@offers.each { |o| @total = @total + o.price }
			return @total / @offers.length
	end

	def self.search(id)
			return find(:all, :conditions => "item_id = #{id}")
	end

	def self.import
    logger.silence do
      Dir.glob(File.join('/home', 'dominik','code','rails', "*.dump")).sort.each do |file|
        pp file
        next if ProcessedDumps.find_by_name(File.split(file)[1])
        
        @sql = []
        @count = 0
        @csvcount = 0
        csv = CSV::Reader.parse(File.open(file))
        offers = Offer.count
        procDump = ProcessedDumps.new(:name => File.split(file)[1])
		
    	csv.each do |row|
          @csvcount += 1
#          next if @csvcount < 6000  
          next if row[0] == "orderid"
          duration = row[11].split(':')[0]
          issued = Date.parse(row[10])
    	  reported = DateTime.parse(row[14].split('.')[0]).strftime('%Y-%m-%d	%H:%M:%S')
    
     	  @sql.push "(#{row[0]}, #{row[1]}, #{row[2]}, #{row[3]}, #{row[6]}, #{row[4]}, #{row[7]}, #{row[8]}, #{row[9]},'#{issued}',#{duration},#{row[12]},'#{reported}','#{issued + duration.to_i}')"
          
          if @count == 200
		    ActiveRecord::Base.connection.insert("INSERT INTO offers(id,region_id,solarsystem_id,station_id,price,item_id,volume_min,volume_remain,volume_enter,issued,duration,range,reported,expires) VALUES" + @sql.join(',') + "ON DUPLICATE KEY UPDATE volume_remain=VALUES(volume_remain), reported=VALUES(reported);")
			print "."
            @count = 0
			@sql = []
          end
          @count += 1
        end
        ActiveRecord::Base.connection.insert("INSERT INTO offers(id,region_id,solarsystem_id,station_id,price,item_id,volume_min,volume_remain,volume_enter,issued,duration,range,reported,expires) VALUES" + @sql.join(',') + "ON DUPLICATE KEY UPDATE volume_remain=VALUES(volume_remain), reported=VALUES(reported);") if !@sql.empty?
        procDump.offers = Offer.count - offers
        procDump.save!
     end
    end
  end
end
#			rescue ActiveRecord::StatementInvalid => err
	#			update = "UPDATE prices SET price=#{row[6]}, volume_remain=#{row[8]}, reported='#{reported}'WHERE id=#{row[0]} LIMIT 1;"
		#		ActiveRecord::Base.connection.update(update)
		#	end



